/** sps_exist_req.cpp - implemention of checking usbkey exist request
 */

#include "sps_config.h"

#define SJN_EXIST_USBKEY                  "existUsbKey"

SpsExistReq::SpsExistReq(const std::string& ip, const std::string& mac)
  : SpsReq(ip, mac)
  , exist_(false)
{
}

SpsExistReq::~SpsExistReq()
{
}

std::string SpsExistReq::getResponse()
{
  if (err_ != ESPS_SUCCESS) {
    return SpsReq::getResponse();
  }

  json v;

  v[SJN_TYPE] = 1;
  v[SJN_CODE] = code_;
  v[SJN_RESULT_STATUS_CODE] = getResultStatusCode();
  v[SJN_RESULT_CODE] = getResultCode();
  v[SJN_RESULT_DESC] = getResultDesc();
  v[SJN_SESSION_ID] = session_;
  v[SJN_AGENT_CLIENT_IP] = local_ip_;
  v[SJN_ALGORITHM] = msgalgo_;

  json d;
  d[SJN_EXIST_USBKEY] = exist_;
  
  v[SJN_RESULT_DATA] = d;
  
  v[SJN_SIGNATURE] = generateVerify(v);

  return v.to_string();
}

/*******************************************************************************
 * Protected functions                                                         *
 ******************************************************************************/

int SpsExistReq::doit()
{
  /* 
   * TODO: Check whether usbkey is exist.
   *       If usbkey exist, set varible *exist_* true.
   *       Otherwise, set it false.
   */
  
  return ESPS_SUCCESS;
}

std::string SpsExistReq::generateVerify(const json& v)
{
  std::list<std::string> l;

  l.push_back(v[SJN_TYPE].as_string());
  l.push_back(v[SJN_CODE].as_string());
  l.push_back(v[SJN_RESULT_STATUS_CODE].as_string());
  l.push_back(v[SJN_RESULT_CODE].as_string());
  l.push_back(v[SJN_RESULT_DESC].as_string());
  l.push_back(v[SJN_SESSION_ID].as_string());
  l.push_back(v[SJN_AGENT_CLIENT_IP].as_string());
  l.push_back(v[SJN_ALGORITHM].as_string());

  json d = v[SJN_RESULT_DATA];
  l.push_back(d[SJN_EXIST_USBKEY].as_string());

  l.push_back(sps_priv_key);

  l.sort();

  std::string msg;
  std::list<std::string>::const_iterator i;
  for (i = l.begin(); i != l.end(); i++) {
    msg += (*i + "&");
  }

  msg.erase(msg.end() - 1);

  return getHash(msg);
}
